#!/usr/bin/env python
#
# Copyright 2007 Free Software Foundation, Inc.
# 
# This file is part of GNU Radio
# 
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# 
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
# 

from gnuradio import gr, gr_unittest, xstar
from random import random
from copy import copy

class qa_reed_solomon (gr_unittest.TestCase):

    def setUp (self):
	self.packet_len = 63
	self.fec_len = 21
	self.payload_len = self.packet_len - self.fec_len
	self.sample_payload = ("0123456789" * (self.payload_len / 10 + 1))[:self.payload_len]

	self.rs = xstar.reed_solomon(self.packet_len, self.fec_len)

    def tearDown (self):
        self.rs = None

    def test_001_encode_size (self):
	fec = self.rs.encode(self.sample_payload)

	self.assertEqual(len(fec), self.fec_len)

    def test_002_decode_error_report (self):
	# We send in uncorrectable (completely bogus) data
	# so we should get en empty string back
	payload = self.rs.decode("x" * self.packet_len)

	self.assertEqual(len(payload), 0)

    def test_003_decode (self):
	fec = self.rs.encode(self.sample_payload)
	decoded_payload = self.rs.decode(self.sample_payload + fec)

	self.assertEqual(self.sample_payload, decoded_payload)

    def test_003_decode_with_errors (self):
	fec = self.rs.encode(self.sample_payload)

        # Concatenate payload and FEC
	# we use a list because we can modify it
	packet = [x for x in self.sample_payload] + [x for x in fec]

	for test_no in range(100):
	    p = copy(packet)

	    # Up to fec_len / 2 bytes of errors should be correctable
	    for mod_no in range(self.fec_len / 2):
		mod_pos = int(random() * len(p))
		# Flip all bits in this byte
		p[mod_pos] = chr(ord(p[mod_pos]) ^ 0xFF)
		decoded_payload = self.rs.decode("".join(p))

		self.assertEqual(self.sample_payload, decoded_payload)

if __name__ == '__main__':
    gr_unittest.main ()
